package xin.marcher.module.inventory.mq.consumer.listener;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Component;
import xin.marcher.module.common.enums.inventory.InventoryDeductionTypeEnum;
import xin.marcher.module.common.utils.JsonUtil;
import xin.marcher.module.inventory.domain.bo.InventoryDetail;
import xin.marcher.module.inventory.repository.InventoryRepository;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 处理 库存扣减明细的记录消息
 */
@Slf4j
@Component
public class InventoryDetailListener implements MessageListenerConcurrently {

    @Resource
    private InventoryRepository inventoryRepository;

    @Override
    public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
        try {
            log.info("执行库存扣减明细保存，消息数量：{}", list.size());
            List<InventoryDetail> inventoryDetailList = new ArrayList<>(list.size());
            for (MessageExt messageExt : list) {
                String msg = new String(messageExt.getBody());

                InventoryDetail inventoryDetail = JsonUtil.json2Object(msg, InventoryDetail.class);
                inventoryDetailList.add(inventoryDetail);
            }

            inventoryRepository.saveInventoryDetailList(inventoryDetailList, InventoryDeductionTypeEnum.INVENTORY_DETAIL_DEDUCTIONS_TYPE.getCode());
        } catch (DuplicateKeyException ex) {
            log.error("consume repeat, 库存扣减明细重复记录,不再重复执行", ex);
            return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
        } catch (Exception e) {
            log.error("consume error, 库存扣减明细保存失败", e);
            // 本次消费失败，下次重新消费
            return ConsumeConcurrentlyStatus.RECONSUME_LATER;
        }
        return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
    }
}
